from django.db import models
from django.conf import settings

class Warehouse(models.Model):
    name = models.CharField(max_length=100, verbose_name='仓库名称')
    location = models.CharField(max_length=255, verbose_name='位置')
    TYPE_CHOICES = (
        ('normal', '常温'),
        ('cold', '冷藏'),
        ('frozen', '冷冻'),
    )
    type = models.CharField(max_length=20, choices=TYPE_CHOICES, verbose_name='仓库类型')
    capacity = models.DecimalField(max_digits=10, decimal_places=2, verbose_name='容量')
    manager = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.SET_NULL, null=True, related_name='managed_warehouses')
    STATUS_CHOICES = (
        ('active', '启用'),
        ('inactive', '停用'),
    )
    status = models.CharField(max_length=20, choices=STATUS_CHOICES, default='active', verbose_name='状态')
    created_at = models.DateTimeField(auto_now_add=True, verbose_name='创建时间')
    updated_at = models.DateTimeField(auto_now=True, verbose_name='更新时间')
    
    class Meta:
        verbose_name = '仓库'
        verbose_name_plural = verbose_name
        
    def __str__(self):
        return self.name


# 在同一个文件中继续添加

class Inventory(models.Model):
    product = models.ForeignKey('products.Product', on_delete=models.CASCADE, related_name='inventories', verbose_name='产品')
    warehouse = models.ForeignKey(Warehouse, on_delete=models.CASCADE, related_name='inventories', verbose_name='仓库')
    current_stock = models.PositiveIntegerField(default=0, verbose_name='当前库存')
    min_stock = models.PositiveIntegerField(verbose_name='最低库存')
    max_stock = models.PositiveIntegerField(null=True, blank=True, verbose_name='最大库存')
    purchase_date = models.DateField(null=True, blank=True, verbose_name='进货日期')
    expiry_date = models.DateField(null=True, blank=True, verbose_name='到期日期')
    STATUS_CHOICES = (
        ('normal', '正常'),
        ('warning', '预警'),
        ('overflow', '超量'),
        ('expired', '过期'),
    )
    status = models.CharField(max_length=20, choices=STATUS_CHOICES, default='normal', verbose_name='状态')
    created_at = models.DateTimeField(auto_now_add=True, verbose_name='创建时间')
    updated_at = models.DateTimeField(auto_now=True, verbose_name='更新时间')
    
    class Meta:
        verbose_name = '库存'
        verbose_name_plural = verbose_name
        unique_together = ('product', 'warehouse')
        indexes = [
            models.Index(fields=['status']),
            models.Index(fields=['expiry_date']),
        ]
        
    def __str__(self):
        return f'{self.product.name} - {self.warehouse.name}'

class InventoryRecord(models.Model):
    inventory = models.ForeignKey(Inventory, on_delete=models.CASCADE, related_name='records', verbose_name='库存')
    OPERATION_CHOICES = (
        ('in', '入库'),
        ('out', '出库'),
        ('adjust', '调整'),
        ('transfer', '转移'),
    )
    operation_type = models.CharField(max_length=20, choices=OPERATION_CHOICES, verbose_name='操作类型')
    quantity = models.IntegerField(verbose_name='数量')
    operator = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE, related_name='inventory_operations', verbose_name='操作员')
    source_warehouse = models.ForeignKey(Warehouse, on_delete=models.SET_NULL, null=True, blank=True, related_name='outgoing_transfers', verbose_name='源仓库')
    target_warehouse = models.ForeignKey(Warehouse, on_delete=models.SET_NULL, null=True, blank=True, related_name='incoming_transfers', verbose_name='目标仓库')
    # 在 InventoryRecord 模型中
    related_order = models.ForeignKey('orders.Order', on_delete=models.SET_NULL, null=True, blank=True, related_name='inventory_records', verbose_name='相关订单')
    note = models.TextField(blank=True, verbose_name='备注')
    created_at = models.DateTimeField(auto_now_add=True, verbose_name='创建时间')
    
    class Meta:
        verbose_name = '库存记录'
        verbose_name_plural = verbose_name
        indexes = [
            models.Index(fields=['operation_type']),
            models.Index(fields=['created_at']),
        ]
        
    def __str__(self):
        return f'{self.get_operation_type_display()} - {self.inventory.product.name}'


class PurchaseOrder(models.Model):
    order_number = models.CharField(max_length=50, unique=True, verbose_name='订单编号')
    supplier = models.CharField(max_length=100, verbose_name='供应商')
    purchaser = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE, related_name='purchase_orders', verbose_name='采购员')
    total_amount = models.DecimalField(max_digits=10, decimal_places=2, verbose_name='总金额')
    STATUS_CHOICES = (
        ('pending', '待确认'),
        ('confirmed', '已确认'),
        ('received', '已收货'),
        ('cancelled', '已取消'),
    )
    status = models.CharField(max_length=20, choices=STATUS_CHOICES, default='pending', verbose_name='状态')
    remark = models.TextField(blank=True, null=True, verbose_name='备注')
    created_at = models.DateTimeField(auto_now_add=True, verbose_name='创建时间')
    updated_at = models.DateTimeField(auto_now=True, verbose_name='更新时间')
    
    class Meta:
        verbose_name = '采购订单'
        verbose_name_plural = verbose_name
        indexes = [
            models.Index(fields=['status']),
            models.Index(fields=['supplier']),
        ]
        
    def __str__(self):
        return f'采购订单 #{self.order_number}'
    
    def save(self, *args, **kwargs):
        # 如果是新创建的订单，生成订单编号
        if not self.order_number:
            import datetime
            import random
            date_str = datetime.datetime.now().strftime('%Y%m%d')
            random_num = random.randint(1000, 9999)
            self.order_number = f'PO{date_str}{random_num}'
        super().save(*args, **kwargs)


class PurchaseOrderItem(models.Model):
    purchase_order = models.ForeignKey(PurchaseOrder, on_delete=models.CASCADE, related_name='items', verbose_name='采购订单')
    product = models.ForeignKey('products.Product', on_delete=models.CASCADE, related_name='purchase_items', verbose_name='产品')
    quantity = models.PositiveIntegerField(verbose_name='数量')
    unit_price = models.DecimalField(max_digits=10, decimal_places=2, verbose_name='单价')
    total_price = models.DecimalField(max_digits=10, decimal_places=2, verbose_name='总价')
    warehouse = models.ForeignKey(Warehouse, on_delete=models.CASCADE, related_name='purchase_items', verbose_name='仓库')
    created_at = models.DateTimeField(auto_now_add=True, verbose_name='创建时间')
    
    class Meta:
        verbose_name = '采购订单明细'
        verbose_name_plural = verbose_name
        
    def __str__(self):
        return f'{self.product.name} x {self.quantity}'
    
    def save(self, *args, **kwargs):
        # 自动计算总价
        self.total_price = self.quantity * self.unit_price
        super().save(*args, **kwargs)